package com.bst.bsj.portal.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.DeflateDecompressingEntity;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.homewaimai.common.lang.StringUtil;

public class HttpClient4ServicePool {

    private static final Log                      logger                = LogFactory.getLog(HttpClient4ServicePool.class);

    /**
     * 连接池里的最大连接数
     */
    public static final int                       MAX_TOTAL_CONNECTIONS = 100;

    /**
     * 每个路由的默认最大连接数
     */
    public static final int                       MAX_ROUTE_CONNECTIONS = 50;

    /**
     * 连接超时时间
     */
    public static final int                       CONNECT_TIMEOUT       = 6000;

    /**
     * 套接字超时时间
     */
    public static final int                       SOCKET_TIMEOUT        = 8000;

    /**
     * 连接池中 连接请求执行被阻塞的超时时间
     */
    public static final long                      CONN_MANAGER_TIMEOUT  = 10000;

    /**
     * http连接相关参数
     */
    private static HttpParams                     parentParams;

    /**
     * http线程池管理器
     */
    private static PoolingClientConnectionManager cm;

    /**
     * http客户端
     */
    private static HttpClient                     httpClient;

    /**
     * 初始化http连接池，设置参数、http头等等信息
     */
    static {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
        cm = new PoolingClientConnectionManager(schemeRegistry);
        cm.setMaxTotal(MAX_TOTAL_CONNECTIONS);
        cm.setDefaultMaxPerRoute(MAX_ROUTE_CONNECTIONS);
        parentParams = new BasicHttpParams();
        parentParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        parentParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        parentParams.setParameter(ClientPNames.CONN_MANAGER_TIMEOUT, CONN_MANAGER_TIMEOUT);
        parentParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECT_TIMEOUT);
        parentParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIMEOUT);
        parentParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        parentParams.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
        // 设置头信息,模拟浏览器
        Collection<Header> collection = new ArrayList<Header>();
        collection.add(new BasicHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)"));
        collection.add(new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
        collection.add(new BasicHeader("Accept-Language", "zh-cn,zh,en-US,en;q=0.5"));
        collection.add(new BasicHeader("Accept-Charset", "ISO-8859-1,utf-8,gbk,gb2312;q=0.7,*;q=0.7"));
        collection.add(new BasicHeader("Accept-Encoding", "gzip, deflate"));
        parentParams.setParameter(ClientPNames.DEFAULT_HEADERS, collection);
        httpClient = new DefaultHttpClient(cm, parentParams);
    }

    public static HttpClient getHttpClient() {
        return httpClient;
    }

    public static String post(String url, Map<String, String> params) {
        HttpClient httpclient = getHttpClient();
        String body = null;

        HttpPost post = postForm(url, params);

        body = invoke(httpclient, post);

        return body;
    }

    public static String post(String url, String json) {
        HttpClient httpclient = getHttpClient();
        String body = null;

        HttpPost post = new HttpPost(url);
        post.setHeader("Content-type", "application/json");

        StringEntity params = new StringEntity(json, Consts.UTF_8);
        post.setEntity(params);

        body = invoke(httpclient, post);

        return body;
    }

    public static String post(String url) {
        return post(url, "");
    }

    public static String get(String url) {
        HttpClient httpclient = getHttpClient();
        String body = null;

        HttpGet get = new HttpGet(url);
        body = invoke(httpclient, get);

        return body;
    }

    private static String invoke(HttpClient httpclient, HttpUriRequest request) {

        HttpResponse response;
        String body = "";
        try {
            response = sendRequest(httpclient, request);
            body = paseResponse(response);
        } catch (Exception e) {
            request.abort();
            logger.error("httpclient pool error", e);
        }
        return body;
    }

    private static String paseResponse(HttpResponse response) throws ParseException, IOException {
        HttpEntity entity = response.getEntity();
        Header ceheader = entity.getContentEncoding();
        if (ceheader != null) {
            for (HeaderElement element : ceheader.getElements()) {
                if (element.getName().equalsIgnoreCase("gzip")) {
                    entity = new GzipDecompressingEntity(response.getEntity());
                    response.setEntity(entity);
                    break;
                }
                if (element.getName().equalsIgnoreCase("deflate")) {
                    entity = new DeflateDecompressingEntity(response.getEntity());
                    response.setEntity(entity);
                    break;
                }
            }
        }

        String body = null;
        String charset = "UTF-8";
        if (null != ContentType.getOrDefault(entity).getCharset()) {
            if (StringUtil.isNotBlank(ContentType.getOrDefault(entity).getCharset().name())) {
                charset = ContentType.getOrDefault(entity).getCharset().name();
            }
        }
        body = EntityUtils.toString(entity, charset);
        EntityUtils.consume(entity);

        return body;
    }

    private static HttpResponse sendRequest(HttpClient httpclient, HttpUriRequest request)
                                                                                          throws ClientProtocolException,
                                                                                          IOException {
        HttpResponse response = null;
        response = httpclient.execute(request);
        return response;
    }

    private static HttpPost postForm(String url, Map<String, String> params) {

        HttpPost httpost = new HttpPost(url);

        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();

            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                nvps.add(new BasicNameValuePair(key, params.get(key)));
            }
            httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        }

        return httpost;
    }

    // public static void main(String[] args) {
    //
    // String str =
    // post("https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=AIzaSyCkZoVFFj5412x4dKFyFq__yydcyTO7jec");
    // System.out.println(str);
    // }
}
